package com.flame.workflow.ru.controller;

import java.io.File;

import javax.servlet.http.HttpServletResponse;

import com.flame.core.protocol.Result;
import com.flame.core.utils.HttpUtils;
import com.flame.workflow.ru.controller.vo.InstanceFilesUploadVo;
import com.flame.workflow.ru.entity.InstanceFile;
import com.flame.workflow.ru.service.InstanceFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 *
 * @author wuxintong😺😺😺
 * @since 2023/11/7
 */
@RestController
public class InstanceFileController {

    @Autowired
    private InstanceFileService instanceFileService;

    @PostMapping("/workflow/ru/instance/file/list")
    public Result listInstanceFiles(@RequestBody InstanceFile instanceFile) {
        return Result.success(instanceFileService.listInstanceFiles(instanceFile));
    }

    @PostMapping("/workflow/ru/file/upload")
    public Result uploadFile(InstanceFilesUploadVo instanceFilesUploadVo) {
        for (MultipartFile file : instanceFilesUploadVo.getFileList()) {
            instanceFileService.saveFile(instanceFilesUploadVo.getInstancdId(), file);
        }
        return Result.success();
    }

    /**
     * 下载文件
     */
    @PostMapping("/workflow/ru/file/download")
    public void downloadFile(@RequestBody InstanceFile instanceFile, HttpServletResponse response) {
        File file = instanceFileService.getFile(instanceFile.getFileId());
        InstanceFile dbInstanceFile = instanceFileService.getFileInfo(instanceFile.getFileId());
        String fileFullName = dbInstanceFile.getFileName() + "." + dbInstanceFile.getFileType();
        HttpUtils.writeFile(response, file, fileFullName);
    }
}
